<template>
  <a-modal
    :title="siteInfo ? '更新站点' : '新增站点'"
    :visible="true"
    destroyOnClose
    @ok="handleOk"
    @cancel="$emit('close-modal')"
    :confirmLoading="requestLoading"
    okText="确定"
    cancelText="取消"
  >
    <a-form-model
      :model="form"
      :rules="formRules"
      ref="ruleForm"
      labelAlign="left"
      :label-col="{ span: 4 }"
      :wrapperCol="{ span: 18 }">
      <a-form-model-item label="站点名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入站点名称" />
      </a-form-model-item>
      <a-form-model-item label="站点url" prop="url">
        <a-input v-model="form.url" placeholder="请输入站点url" />
      </a-form-model-item>
      <a-form-model-item label="描述信息" prop="url">
        <a-textarea :rows="3" v-model="form.siteDesc" placeholder="请输入站点描述信息" />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
export default {
  props: {
    folderId: {
      type: String,
      required: true
    },
    siteInfo: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      requestLoading: false,
      form: {
        name: null,
        url: null,
        siteDesc: null
      },
      formRules: {
        name: [
          { required: true, message: '请输入站点名称', trigger: 'blur', whitespace: true },
          { max: 64, message: '文件夹名称最大长度不能超过64位', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入站点url', trigger: 'blur', whitespace: true },
          { type: 'url', message: '请输入正确的站点url', trigger: 'blur' }
        ],
        siteDesc: [
          { required: true, message: '请输入站点描述信息', trigger: 'blur', whitespace: true },
          { max: 64, message: '描述信息最大长度不能超过64位', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    if (this.siteInfo) {
      const { name, url, id, siteDesc } = this.siteInfo
      this.form = { name, url, id, siteDesc }
    }
  },

  methods: {
    handleOk () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          this.requestLoading = true
          try {
            const path = `/gimishare/api/v1/sites/${this.siteInfo ? 'update' : 'create'}`
            await this.$axios.post(path, {
              ...this.form,
              folderId: this.folderId
            })
            this.$message.success(this.siteInfo ? '更新站点成功' : '创建站点成功')
            this.$emit('close-modal', true)
          } catch (error) {
            console.log(error)
          } finally {
            this.requestLoading = false
          }
        }
      })
    }
  }
}
</script>
